import jwt
from jwt import exceptions
from django.conf import settings
from rest_framework.response import Response
from users.models import User

def check_login(func):
    def wrapper(self,request,*args,**kwargs):
        # 获取token

        token = request.headers.get("token")
        # 2.根据token 判断用户是否登录
        #    已登录，  则获取payload中的username， 根据用户名查询用户对象
        #    未登录，  直接返回响应， ‘token过期’ 或者 ‘非法的token’
        try:
            payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms="HS256")
        except exceptions.ExpiredSignature:
            return Response({"code": 204, "msg": "token过期"})

        except exceptions.DecodeError:
            return Response({"code": 204, "msg": "非法的token"})

        # 获取username
        username = payload.get("username")
        user = User.objects.get(username=username)
        request.user = user

        # 3.参数func的执行
        return func(self, request, *args, **kwargs)

    return wrapper